package com.duoduo.mcc.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duoduo.mcc.bean.MccMessage;

/**
 * 消息队列管理
 * @author cgs1999@126.com
 * @date 2018年11月1日下午6:02:28
 */
public class MccQueueService {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private static Map<String, ConcurrentLinkedQueue<MccMessage>> QueueMap = new HashMap<String, ConcurrentLinkedQueue<MccMessage>>();
	private static Map<String, Long> restartTimeMap = new HashMap<String, Long>();
	private MccCollectionService mccCollectionService;

	public MccQueueService(MccCollectionService mccCollectionService) {
		this.mccCollectionService = mccCollectionService;
	}

	public boolean addMsg(String e164, MccMessage ntf) {
		synchronized (e164) { // 对每个会议做线程同步保护
			if(ntf!=null) {
				if (logger.isDebugEnabled()) {
					logger.debug("已经添加消息到queue中");
				}

				ConcurrentLinkedQueue<MccMessage> queue = QueueMap.get(e164);
				if (queue == null) {
					if (logger.isDebugEnabled()) {
						logger.debug("当前会议 {} 没有队列，需要创建", e164);
					}
					queue = new ConcurrentLinkedQueue<MccMessage>();
				}
				queue.offer(ntf);
				QueueMap.put(e164, queue);
				return true;
			} else {
				ConcurrentLinkedQueue<MccMessage> queue = QueueMap.get(e164);
				if (queue == null || queue.isEmpty()) {
					mccCollectionService.delSet(e164);
					setRestartTime(e164, null);
					return true;
				}
				return false;
			}
		}

	}

	public ConcurrentLinkedQueue<MccMessage> getLinkedQueue(String e164) {
		ConcurrentLinkedQueue<MccMessage> queue = QueueMap.get(e164);
		return queue;
	}

	public MccMessage getQueue(String e164) {
		ConcurrentLinkedQueue<MccMessage> queue = QueueMap.get(e164);

		synchronized (queue) {
			if (!queue.isEmpty()) {
				return queue.poll();
			}
			return null;

		}
	}

	public List<MccMessage> getListQueue(String e164) {
		List<MccMessage> listQueue = new ArrayList<MccMessage>();
		ConcurrentLinkedQueue<MccMessage> queue = QueueMap.get(e164);
		for (int i = 0; i < 100; i++) {
			synchronized (queue) {
				if (!queue.isEmpty()) {
					listQueue.add(queue.poll());
				}
			}
		}

		return listQueue;

	}

	public MccMessage readOnlyQueue(String e164) {
		ConcurrentLinkedQueue<MccMessage> queue = QueueMap.get(e164);
		if (!queue.isEmpty()) {// 只读操作 不需要做线程同步保护
			return queue.peek();
		}
		return null;
	}

	public Long getRestartTime(String e164) {
		Long restartTime = restartTimeMap.get(e164);
		return restartTime;
	}

	public void setRestartTime(String e164, Long restartTime) {
		if (restartTime == null) {// 消息队列处理完，清除e164的残留信息
			restartTimeMap.remove(e164);
		} else {
			restartTimeMap.put(e164, restartTime);
		}
	}

}
